import Base from 'models/base';

import SystemUtil from 'utils/systemUtil';

export default class MenuData extends Base {
  constructor(menus) {
    super();

    let menuMap = {};
    let menusList = this.setMenuData(menus, menuMap);
    this.menusList = menusList;
    this.menuMap = menuMap;
    this.isCollapse = false;
  }

  setMenuData(menus, menuMap) {
    let menuList = [];
    for (let i = 0; i < menus.length; i++) {
      let menu = menus[i];
      menu = _.cloneDeep(menu);
      if (menu.isMenu !== 1) {
        continue;
      }
      let permissionId = menu.permissionId;
      menuMap[permissionId] = menu;

      let children = menu.children;
      if (!SystemUtil.isEmpty(children)) {
        children = this.setMenuData(children, menuMap);
        menu.children = children;
      }
      menuList.push(menu);
    }
    return menuList;
  }

  getMenuPath(path) {
    let menuMap = this.menuMap;
    let menu = _.find(menuMap, obj => {
      return obj.path === path;
    });
    if (menu === undefined) {
      return [];
    }

    let menus = [menu];
    let id = menu.permissionParent;
    while (id !== 0) {
      let menuObj = menuMap[id];
      if (menuObj === undefined) {
        break;
      }
      menus.push(menuObj);
      id = menuObj.permissionParent;
    }
    menus = menus.reverse();
    return menus;
  }
}
